<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('pdk_Document_model')) return; 
/**
 * SPIP Plugin Development Kit
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage pdk
 * @category   outils
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/Developmet-Kit
 * @version    1.0.0
 */

include_spip('classes/pdk_model');
/**
 *  Document Class
 * 
 * 	This model represents SPIP document 
 *
 * @package		plugins
 * @subpackage	pdk
 * @category	outils
 * @author		Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @link		http://www.spip-contrib.net/Developmet-Kit
 */
class pdk_Document_model extends pdk_Model {
    /**
    * Document input name
    */
    var $document_input_name = 'document';
    
    /**
     *  Document allowed types
     */
    var $allowed_types = 'gif|jpg|png|jpeg|bmp|doc'; //TODO: Прописать сюда все допустимые SPIP-ом типы, а еще лучше взять их из таблички spip_types_documents
    
    public function __construct() {
        parent::__construct();
        $this->config_model();        
    }
    
    function config_model() {
        // Define main table:
        $this->main_table = 'spip_documents';
        
        // Define primary key:
        $this->primary_key = 'id_document';
        
        // Define main table fields:
        $this->main_fields['id_document'] = 'id_document'; 
        $this->main_fields['id_vignette'] = 'id_vignette';
        $this->main_fields['extension'] = 'extension';
        $this->main_fields['titre'] = 'titre';
        $this->main_fields['date'] = 'date';
        $this->main_fields['descriptif'] = 'descriptif';
        $this->main_fields['fichier'] = 'fichier'; 
        $this->main_fields['taille'] = 'taille';
        $this->main_fields['largeur'] = 'largeur';
        $this->main_fields['hauteur'] = 'hauteur';
        $this->main_fields['mode'] = 'mode';
        $this->main_fields['distant'] = 'distant';
        $this->main_fields['maj'] = 'maj';                     
                                                                                 
         // Define validation rules:
         $this->validation->set_rules( 
            array(
               array(
                     'field'   => 'id_document',
                     'label'   => 'ID document',
                     'rules'   => 'is_natural'
                  ),
               array(
                     'field'   => 'id_vignette',
                     'label'   => 'ID vignette',
                     'rules'   => 'is_natural'
                  )
            )
         );                                       
    }
    
    /**
     *  Override parent method to add document uploading
     *  Inserting new document implies binding file uploading
     * 
     *  @param array $data Array with some data (like titre or descriptif). Another data will be added automatically
     */
    function insert($data = array(), $clear_id = false) { //TODO: Добавить третий параметр - массив связей длбавляемого документа с объектами, и вставить эти данные в табличку spip_documents_liens с помощью модели pdk_Document_lien_model
        $insert_flag = true;
            
            include_spip('classes/pdk_upload');
            $config = array();
            $config['upload_path'] = _DIR_IMG;
            $config['allowed_types'] = $this->allowed_types; 
            $config['max_size'] = '2048';
            $config['encrypt_name'] = TRUE;
            $uploader = new pdk_Upload($config);
        
            if ($uploader->do_upload($this->document_input_name)) { 
                $file_data = $uploader->data();
                
                // Check subdirectory in IMG and create if nessecary
                $extension = str_replace('.','',$file_data['file_ext']);
                if(!file_exists(_DIR_IMG.$extension) or !is_dir(_DIR_IMG.$extension))
                    mkdir(_DIR_IMG.$extension);
                
                // Move file to subdirectory    
                if (rename(_DIR_IMG.$file_data['file_name'], _DIR_IMG.$extension.'/'.$file_data['file_name'])) {
                    // Add some information ot $data array
                    $data['extension'] = $extension;
                    $data['date'] = date('Y-m-d H:i:s');
                    $data['fichier'] = $extension.'/'.$file_data['file_name'];
                    $data['taille'] = $file_data['file_size']*1024;
                    $data['largeur'] = $file_data['is_image'] ? $file_data['image_width'] : 0;
                    $data['hauteur'] = $file_data['is_image'] ? $file_data['image_height'] : 0;
                    //$data['mode'] = 'document'; //TODO: Сдесь можно задавать и image, но document идет по дефолту
                } else $insert_flag = false;
            } else $insert_flag = false;
            
        if ($insert_flag && $id_document = parent::insert($data, $clear_id)) {
            return $id_document;
        } else return false;
    }
}
?>